import { useState, useCallback, useEffect } from 'react';
import { message } from 'antd';
import { http } from './http';

export function usePublish(type) {
  const [newsList, setNewsList] = useState([])  // 存放新闻数据列表
  const { username } = JSON.parse(window.sessionStorage.getItem('news'))

  // 获取publish新闻列表
  const getNewsList = useCallback(async () => {
    const { data } = await http.get(`/news?author=${username}&publishState=${type}&_expand=category`)
    setNewsList(data)
  }, [username, type])

  useEffect(() => {
    getNewsList()
  }, [getNewsList])

  // 点击发布按钮的回调
  const handlePublish = id => {
    http.patch(`/news/${id}`, {
      publishState: 2,
      publishTime: Date.now()
    })
      .then(() => {
        setNewsList(newsList.filter(item => item.id !== id))
        message.success('发布成功！', 2)
      })
      .catch(() => {
        message.error('发布失败！', 2)
      })
  }

  // 点击下线按钮的回调
  const handleSunset = id => {
    http.patch(`/news/${id}`, {
      publishState: 3
    })
      .then(() => {
        setNewsList(newsList.filter(item => item.id !== id))
        message.success('新闻已下线！', 2)
      })
      .catch(() => {
        message.error('新闻下线失败！', 2)
      })
  }

  // 点击删除按钮的回调
  const handleDelete = id => {
    http.delete(`/news/${id}`)
      .then(() => {
        setNewsList(newsList.filter(item => item.id !== id))
        message.success('删除成功！', 2)
      })
      .catch(() => {
        message.error('删除失败！', 2)
      })
  }

  return {
    newsList,
    handlePublish,
    handleSunset,
    handleDelete
  };
}